package com.system.dao;

import com.am.base.BaseDao;
import com.system.uitls.CommonUtil;
import com.system.uitls.IdUtils;
import com.system.uitls.MD5keyBean;
import com.system.vo.User;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

public class UserDao extends BaseDao
{
  public Map<String, Object> findUser(String id)
  {
    String sql = "SELECT name,sex,campus,telephone FROM sys_user WHERE id=?";
    Map map = getSimpleJdbc().queryForMap(sql, new Object[] { id });
    sql = "SELECT role_id FROM sys_user_role WHERE user_id=?";
    List roles = getJdbc().queryForList(sql, new Object[] { id }, String.class);
    map.put("roles", roles.toArray());

    return map;
  }

  public Map<String, String> initPassword(String id)
  {
    Map result = new HashMap();
    try
    {
      String password = new MD5keyBean().getkeyBeanofStr("111111");
      String sql = "update sys_user set password=? where id=?";
      getSimpleJdbc().update(sql, new Object[] { password, id });
      result.put("value", "设置成功");
    }
    catch (Exception ex) {
      result.put("value", "设置失败");
    }

    return result;
  }

  public Map<String, String> delete(String id)
  {
    Map result = new HashMap();
    List sqlList = new ArrayList();
    List params = new ArrayList();
    try
    {
      sqlList.add("DELETE FROM sys_user WHERE id=?");
      params.add(new Object[] { id });

      sqlList.add("DELETE FROM sys_user_role WHERE user_id=?");
      params.add(new Object[] { id });

      batchInTransaction(sqlList, params);

      result.put("type", "success");
      result.put("value", "删除成功");
    }
    catch (Exception ex) {
      result.put("type", "fail");
      result.put("value", "删除失败");
    }

    return result;
  }

  public Map<String, String> update(Map<String, Object> map)
  {
    String id = CommonUtil.nullToEmptyString(map.get("id"));
    String name = CommonUtil.nullToEmptyString(map.get("name"));
    String sex = CommonUtil.nullToEmptyString(map.get("sex"));
    String campus = CommonUtil.nullToEmptyString(map.get("campus"));
    String telephone = CommonUtil.nullToEmptyString(map.get("telephone"));
    String[] roles = (String[])map.get("roles");
    Map result = new HashMap();
    List sqlList = new ArrayList();
    List params = new ArrayList();

    if ("".equals(id))
    {
      try
      {
        String sql = "select count(*) from sys_user where name=?";
        int count = getSimpleJdbc().queryForInt(sql, new Object[] { name });

        if (count >= 1)
        {
          result.put("value", "用户名已经存在,请更换");

          return result;
        }

        String password = new MD5keyBean().getkeyBeanofStr("111111");
        id = IdUtils.getSequence(getJdbc(), "sys_user_id");
        sqlList.add("INSERT INTO sys_user(id,name,password,sex,campus,telephone) VALUES(?,?,?,?,?,?)");
        params.add(new Object[] { id, name, password, sex, campus, telephone });
        for (int i = 0; i < roles.length; i++)
        {
          sqlList.add("INSERT INTO sys_user_role(id,role_id,user_id) VALUES(?,?,?)");
          params.add(new Object[] { IdUtils.getSequence(getJdbc(), "sys_user_role_id"), roles[i], id });
        }

        batchInTransaction(sqlList, params);
        result.put("type", "success");
        result.put("value", "保存成功");
      }
      catch (Exception ex) {
        ex.printStackTrace();
        result.put("type", "fail");
        result.put("value", "保存失败");
      }
    }
    else try {
        sqlList.add("UPDATE sys_user SET name=?,sex=?,campus=?,telephone=? WHERE id=?");
        params.add(new Object[] { name, sex, campus, telephone, id });

        sqlList.add("DELETE FROM sys_user_role WHERE user_id=?");
        params.add(new Object[] { id });

        for (int i = 0; i < roles.length; i++)
        {
          sqlList.add("INSERT INTO sys_user_role(id,role_id,user_id) VALUES(?,?,?)");
          params.add(new Object[] { IdUtils.getSequence(getJdbc(), "sys_user_role_id"), roles[i], id });
        }

        batchInTransaction(sqlList, params);
        result.put("type", "success");
        result.put("value", "修改成功");
      }
      catch (Exception ex)
      {
        ex.printStackTrace();
        result.put("type", "fail");
        result.put("value", "修改失败");
      }


    return result;
  }

  public User checkLogin(String username, String password)
  {
    User user = null;
    MD5keyBean m = new MD5keyBean();
    password = m.getkeyBeanofStr(password);
    String sql = "SELECT id,name,campus FROM sys_user where name=? and password=?";
    List userList = getSimpleJdbc().queryForList(sql, new Object[] { username, password });

    if ((userList != null) && (userList.size() == 1))
    {
      String id = CommonUtil.nullToEmptyString(((Map)userList.get(0)).get("id"));
      String name = CommonUtil.nullToEmptyString(((Map)userList.get(0)).get("name"));
      String campus = CommonUtil.nullToEmptyString(((Map)userList.get(0)).get("campus"));
      user = new User(id, name, campus);
    }

    if ((user != null) && (!user.getName().equals("admin")))
    {
      sql = "SELECT t1.url FROM sys_privilege t1,sys_role_privilege t2,sys_user_role t3 WHERE t2.role_id=t3.role_id AND t3.user_id=? AND t1.id=t2.privilege_id AND t1.pId is not null";
      List list = getJdbc().queryForList(sql, new Object[] { user.getId() }, String.class);
      user.setPrivileges(new HashSet(list));
    }
    return user;
  }

  public List<Map<String, Object>> getCheckPrivildegeUsers()
  {
    String checkUrl = "drug_approve";
    String sql = "SELECT t4.id,t4.name FROM sys_user_role t,sys_user t4,(SELECT role_id FROM sys_privilege t1,sys_role_privilege t2 where t1.id=t2.privilege_id AND t1.url=?) t3 where t3.role_id=t.role_id AND t4.id=t.user_id";
    return getSimpleJdbc().queryForList(sql, new Object[] { checkUrl });
  }

  public Map<String, String> editPassword(Map<String, Object> map)
  {
    String userId = CommonUtil.nullToEmptyString(map.get("userId"));
    String currentPassword = CommonUtil.nullToEmptyString(map.get("currentPassword"));
    String newPassword = CommonUtil.nullToEmptyString(map.get("newPassword"));
    String repeatPassword = CommonUtil.nullToEmptyString(map.get("repeatPassword"));
    Map result = new HashMap();

    currentPassword = new MD5keyBean().getkeyBeanofStr(currentPassword);

    int count = getSimpleJdbc().queryForInt("SELECT COUNT(1) FROM sys_user WHERE id=? AND password=?", new Object[] { userId, currentPassword });
    if (count != 1)
    {
      result.put("type", "error");
      result.put("value", "当前密码输入错误");
      return result;
    }
    if (!newPassword.equals(repeatPassword))
    {
      result.put("type", "error");
      result.put("value", "密码确认错误");
      return result;
    }

    newPassword = new MD5keyBean().getkeyBeanofStr(newPassword);
    String sql = "UPDATE sys_user SET password=? WHERE id=?";
    try {
      getSimpleJdbc().update(sql, new Object[] { newPassword, userId });
      logger.info("UserDao[editPassword] sql:" + sql);
      result.put("type", "success");
      result.put("value", "修改成功");
    }
    catch (Exception ex) {
      logger.error("UserDao[editPassword] sql:" + sql + "\n" + ex.getMessage());
      result.put("type", "error");
      result.put("value", "修改失败");
    }

    return result;
  }
}